package com.alone.wchat.common.net;


import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取主机信息工具类
 * 
 * @author bics
 *
 */
public class HostUtils {
	/**
	 * 获取主机名
	 * 
	 * @return
	 */
	public static String getHostName() {
		try {
			InetAddress address = InetAddress.getLocalHost();
			return address.getHostName();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "-";
	}

	/**
	 * 获取本地IP
	 * 
	 * @return
	 */
	public static String getIp() {
		try {
			InetAddress address = InetAddress.getLocalHost();
			return address.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "-";
	}
	
	/**
	 * 获取公网IP信息；通过http://www.ip138.com <b>貌似国外无法访问</b>
	 * 
	 * @return 公网IP+地理位置+运营商，null--未知ip
	 */
	public static String getPublicIP() {

		String url = "http://www.ip138.com/ips1388.asp";

		Map<String, String> headers = new HashMap<>();
		headers.put("Content-type", "text/html;charset=utf-8");

		byte[] respByteArr = null;
		try {
			respByteArr = HttpClientUtils.get(url, headers);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		if (respByteArr != null) {
			String respStr = "";
			try {
				respStr = new String(respByteArr, "gbk");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			Pattern p = Pattern.compile(".*您的IP地址是：\\[(.*?)\\] 来自：(.*?)<br.*");

			String[] lines = respStr.substring(respStr.indexOf("您的IP地址是")).split("\r\n");
			if (lines.length > 0) {
				Matcher m = p.matcher(lines[0]);
				if (m.matches()) {
					return (m.group(1) + " " + m.group(2));
				}
			}
		}
		return "获取失败";

	}

}